const express = require('express')
const router = express()
const util = require('../../util/novel') ;
const Novel = require('../../api/novels') ;

router.get('/novels',(req,res,next) => {
    if(req.query.q){
        const q = req.query.q;
        const page = req.query.page||1;
        util.query(q,page).then(results =>{
            res.send({code:200,list:results})
        }).catch(error=>{
            console.error(error)
            res.send({code:500,message:'fetch error'})
        })
    }else {
        res.send({code:404,message:'Please input a keyword'})
    }
})
router.get('/novel',(req,res,next) => {
    if(req.query.url){
        util.novel(req.query.url).then(obj=>{
            res.send(obj);
        })
    }else if(req.query.curl){
        util.chapter(req.query.curl).then(obj=>{
            res.send(obj);
        })
    }else {
        res.send({code:404,message:'Please input a novel url'})
    }
})

router.get('/novel/follows',(req,res,next) => {
    const userId = req.query.userId;
    if(!userId){
        res.send({code:404,message:'Not Found'})
    }else {
        Novel.getCollect(userId).then(collect=>{
            res.send({code:200,data:collect,message:'OK'})
        })
    }
})

router.post('/novel/follows',(req,res,next) => {
    Novel.collect(req.body,req.query.f).then(() =>{
        res.send({code:200,message:'OK'})
    }).catch(err=>{
        res.send({code:500,message:err.message})
    })
})

router.post('/novel/read',(req,res,next) => {
    Novel.read(req.body).then(collect =>{
        res.send({code:200,message:'OK'})
    }).catch(err=>{
        res.send({code:500,message:err.message})
    })
})

module.exports = router;